package com.ruoyi.api.interceptor;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.api.annotation.IgnoreAuth;
import com.ruoyi.api.domain.HyToken;
import com.ruoyi.api.service.ApiTokenService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限拦截器
 * @author lixin
 * @date 2021-07-01 15:35
 */

public class ApiAuthorizationInterceptor implements HandlerInterceptor {

	@Autowired
	private ApiTokenService tokenService;

	public static final String LOGIN_TOKEN_KEY = "ApiAuthorization";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

		//支持跨域请求
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Access-Control-Allow-Credentials", "true");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with,ApiAuthorization,X-URL-PATH,content-type");
		response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));

		//让请求，不被缓存，
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Cache-Control", "no-store");
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", 0);

		IgnoreAuth annotation;
		if (handler instanceof HandlerMethod) {
			annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);
		} else {
			return true;
		}

		//如果有@IgnoreAuth注解，则不验证token
		if (annotation != null) {
			return true;
		}

		//从header中获取token
		String token = request.getHeader(LOGIN_TOKEN_KEY);

		if (Validator.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
			token = token.replace(Constants.TOKEN_PREFIX, "");
		}

		//token为空
		if (StrUtil.isBlank(token)) {
			throw new CustomException("你还未登录，是否去登录", 401);
		}

		//查询token信息
		HyToken tokenEntity = tokenService.queryByToken(token);
		if (tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
			throw new CustomException("token失效，请重新登录", 401);
		}

		//设置userId到request里，后续根据userId，获取用户信息
		request.setAttribute("userId", tokenEntity.getUserId());

		return true;
	}



}
